package com.ruoyi.machine.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.machine.EmpEquipment;
import com.ruoyi.common.core.domain.machine.EmpMachine;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.machine.annotation.EquipmentLog;
import com.ruoyi.machine.service.IEmpEquipmentService;
import com.ruoyi.machine.service.IEmpMachineService;
import com.ruoyi.store.domain.EmpStore;
import com.ruoyi.store.service.IEmpStoreService;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 设备列表Controller
 *
 * @author 黄字添
 * @date 2023-12-26
 */
@RestController
@RequestMapping("/machine/equipment")
public class EmpEquipmentController extends BaseController {
    @Autowired
    private IEmpEquipmentService empEquipmentService;
    @Autowired
    private IEmpMachineService empMachineService;
    @Resource
    private IEmpStoreService IEmpStoreService;
    /**
     * 查询设备列表列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:list')")
    @GetMapping("/list")
    public TableDataInfo list(EmpEquipment empEquipment) {
        startPage();
        empEquipment.setDeptId(getDeptId());
        List<EmpEquipment> list = empEquipmentService.selectEmpEquipmentList(empEquipment);
        return getDataTable(list);
    }
    
    
    
    /**
     * 查询未绑定设备列表列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:list')")
    @GetMapping("/getNoUseList")
    public TableDataInfo getNoUseList(EmpEquipment empEquipment) {
        startPage();
        empEquipment.setDeptId(getDeptId());
        List<EmpEquipment> list = empEquipmentService.selectEmpEquipmentNoUseList(empEquipment);
        return getDataTable(list);
    }
    
    /**
     * 获取设备列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:query')")
    @GetMapping(value = "/{equipmentID}")
    public AjaxResult getInfo(@PathVariable("equipmentID") Long equipmentID) {
        return success(empEquipmentService.selectEmpEquipmentByEquipmentID(equipmentID));
    }

    /**
     * 新增设备列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:add')")
    @Log(title = "设备列表", businessType = BusinessType.INSERT)
    @EquipmentLog(title = "新增设备")
    @PostMapping
    public AjaxResult add(@RequestBody EmpEquipment empEquipment) {
        empEquipment.setCreatedTime(new Date());
        EmpStore store = IEmpStoreService.getById(empEquipment.getStoreId());
        if(store!=null) {
        	empEquipment.setDeptId(store.getDept_id().longValue());
        }
        empEquipment.setCreateBy(getUsername());
        empEquipment.setUserId(getUserId());
        return toAjax(empEquipmentService.insertEmpEquipment(empEquipment));
    }

    /**
     * 修改设备列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:edit')")
    @Log(title = "设备列表", businessType = BusinessType.UPDATE)
    @EquipmentLog(title = "修改设备")
    @PutMapping
    public AjaxResult edit(@RequestBody EmpEquipment empEquipment) {
        empEquipment.setUpdatedTime(new Date());
        EmpStore store = IEmpStoreService.getById(empEquipment.getStoreId());
        if(store!=null) {
        	empEquipment.setDeptId(store.getDept_id().longValue());
        }
        empEquipment.setUpdateBy(getUsername());
        empEquipment.setUserId(getUserId());
        return toAjax(empEquipmentService.updateEmpEquipment(empEquipment));
    }

    /**
     * 绑定设备列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:edit')")
    @Log(title = "设备列表", businessType = BusinessType.UPDATE)
    @EquipmentLog(title = "绑定设备")
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/bindEquipment")
    public AjaxResult bindEquipment(@RequestBody EmpMachine empMachine) {
        //获取machineID
        Long machineID = empMachine.getMachineID();
        Long equipmentID = empMachine.getEquipmentID();
        Integer seatNumber = empMachine.getSeatNumber();
        
        //检查该机器和位置是否已经被绑定
        EmpEquipment empEquipmentFind = empEquipmentService.selectEmpEquipmentByMachineIdBindAndSeatNumber(empMachine);
        //判断是否查询回来了结果
        if(empEquipmentFind != null && empEquipmentFind.getEquipmentID() != null){
            //清空旧机台位置
            EmpEquipment empEquipment = new EmpEquipment();
            empEquipment.setEquipmentID(empEquipmentFind.getEquipmentID());
            empEquipment.setUpdatedTime(new Date());
            empEquipment.setUpdatedBy(getUsername());
            empEquipment.setMachineIdBind(0L);
            empEquipment.setSeatNumber(1);
            int res1 = empEquipmentService.updateEmpEquipment(empEquipment);
            if(res1 == 0){
                throw new RuntimeException("empEquipment清空旧机台位置失败");
            }
        }
        //如果seatNumber为1，则执行machine表的更新加新增字段的事务更新
        if(seatNumber == 1){
            empMachine.setUpdatedTime(new Date());
            empMachine.setUpdatedBy(getUsername());
            int res2 = empMachineService.updateEmpMachine(empMachine);
            if(res2 == 0){
                throw new RuntimeException("empMachine更新失败");
            }
            //新增字段的事务更新
            EmpEquipment empEquipment = new EmpEquipment();
            empEquipment.setEquipmentID(equipmentID);
            empEquipment.setUpdatedTime(new Date());
            empEquipment.setUpdatedBy(getUsername());
            empEquipment.setMachineIdBind(machineID);
            empEquipment.setSeatNumber(empMachine.getSeatNumber());
            int res3 = empEquipmentService.updateEmpEquipment(empEquipment);
            if(res3 == 0){
                throw new RuntimeException("empEquipment1更新失败");
            }
            return toAjax(true);
        } else {
            //如果seatNumber不为1，执行新增字段的更新
            //新增字段的更新
            EmpEquipment empEquipment = new EmpEquipment();
            empEquipment.setEquipmentID(equipmentID);
            empEquipment.setUpdatedTime(new Date());
            empEquipment.setUpdatedBy(getUsername());
            empEquipment.setMachineIdBind(machineID);
            empEquipment.setSeatNumber(empMachine.getSeatNumber());
            int res4 = empEquipmentService.updateEmpEquipment(empEquipment);
            if(res4 == 0){
                throw new RuntimeException("empEquipment2更新失败");
            }
        }
        return toAjax(true);
    }
    
    /** 
     * 解绑设备列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:edit')")
    @Log(title = "设备列表", businessType = BusinessType.UPDATE)
    @EquipmentLog(title = "解绑设备")
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/unbindEquipment")
    public AjaxResult unbindEquipment(@RequestBody EmpMachine empMachine) {
        //获取machineID
        Long machineID = empMachine.getMachineID();
        Long equipmentIDRequest = empMachine.getEquipmentID();
        //通过machineID获取typeID equipmentID
        EmpMachine machine = empMachineService.selectEmpMachineByMachineID(machineID);
        Long equipmentIDFind = machine.getEquipmentID();
        //如果machine表查询回来的equipmentID等于当前的equipmentID，则执行旧的解绑
        if(equipmentIDFind.equals(equipmentIDRequest)){
            empMachine.setUpdatedTime(new Date());
            empMachine.setUpdatedBy(getUsername());
            empMachine.setEquipmentID(null);
            int res1 = empMachineService.updateEmpMachine(empMachine);
            if(res1 == 0){
                throw new RuntimeException("empMachine解绑失败");
            }
        }
        //执行empEquipment表的解绑
        EmpEquipment empEquipment = new EmpEquipment();
        empEquipment.setEquipmentID(equipmentIDRequest);
        empEquipment.setUpdatedTime(new Date());
        empEquipment.setUpdatedBy(getUsername());
        empEquipment.setMachineIdBind(0L);
        empEquipment.setSeatNumber(1);
        int res1 = empEquipmentService.updateEmpEquipment(empEquipment);
        if(res1 == 0){
            throw new RuntimeException("empEquipment解绑失败");
        }
        return toAjax(true);
    }

    /**
     * 删除设备列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:remove')")
    @Log(title = "设备列表", businessType = BusinessType.DELETE)
    @EquipmentLog(title = "删除设备")
    @DeleteMapping("/{equipmentIDs}")
    public AjaxResult remove(@PathVariable Long[] equipmentIDs) {
        return toAjax(empEquipmentService.deleteEmpEquipmentByEquipmentIDs(equipmentIDs));
    }

    /**
     * 导出设备列表列表
     */
    @PreAuthorize("@ss.hasPermi('machine:equipment:export')")
    @Log(title = "设备列表", businessType = BusinessType.EXPORT)
    @EquipmentLog(title = "导出设备")
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmpEquipment empEquipment) {
        List<EmpEquipment> list = empEquipmentService.selectEmpEquipmentList(empEquipment);
        ExcelUtil<EmpEquipment> util = new ExcelUtil<EmpEquipment>(EmpEquipment.class);
        util.exportExcel(response, list, "设备列表数据");
    }
}
